#include "TerrainShader.h"
#include "Light.h"
#include "Texture.h"

using namespace Graphics;
RTTI_DEFINITIONS(TerrainShader)

TerrainShader::TerrainShader(void)
	:Shader("TerrainShader","")
{
}

TerrainShader::~TerrainShader(void)
{
}

bool TerrainShader::Initialize()
{
	Graphics::D3DDevice* nDevice = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();
	bool result = InitializeShader(nDevice->GetWindowsSettings().WindowHandle, 
								   "..\\..\\assets\\shaders\\terrain.vs", 
								   "..\\..\\assets\\shaders\\terrain.ps");

	return result;
}

void TerrainShader::Deinitialize()
{
	DeinitializeShader();
}

bool TerrainShader::Render(int indexCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, Light* light, Texture* texture)
{
	bool result = SetShaderParameters(worldMatrix, viewMatrix, projectionMatrix, light, texture);

	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();

	result = RenderShader(device, indexCount);

	return result;
}

bool TerrainShader::InitializeShader(HWND hwnd, const char* vsFilename,  const char* psFilename)
{
	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();
	if(Shader::InitializeShader(device, hwnd, vsFilename, psFilename))
	{
		D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
		polygonLayout[0].SemanticName = "POSITION";
		polygonLayout[0].SemanticIndex = 0;
		polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
		polygonLayout[0].InputSlot = 0;
		polygonLayout[0].AlignedByteOffset = 0;
		polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		polygonLayout[0].InstanceDataStepRate = 0;

		polygonLayout[1].SemanticName = "TEXCOORD";
		polygonLayout[1].SemanticIndex = 0;
		polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
		polygonLayout[1].InputSlot = 0;
		polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
		polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		polygonLayout[1].InstanceDataStepRate = 0;

		polygonLayout[2].SemanticName = "NORMAL";
		polygonLayout[2].SemanticIndex = 0;
		polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
		polygonLayout[2].InputSlot = 0;
		polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
		polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		polygonLayout[2].InstanceDataStepRate = 0;

		// Get a count of the elements in the layout.
		unsigned int  numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

		// Create the vertex input layout.
		HRESULT result = device->GetDevice()->CreateInputLayout(polygonLayout, numElements, mVertexShaderBuffer->GetBufferPointer(), mVertexShaderBuffer->GetBufferSize(), &mLayout);
		if(FAILED(result))
		{
			return false;
		}

		// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
		mVertexShaderBuffer->Release();
		mVertexShaderBuffer = NULL;

		mPixelShaderBuffer->Release();
		mPixelShaderBuffer = NULL;

		// Create a texture sampler state description.
		D3D11_SAMPLER_DESC samplerDesc;
		samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
		samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.MipLODBias = 0.0f;
		samplerDesc.MaxAnisotropy = 1;
		samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
		samplerDesc.BorderColor[0] = 0;
		samplerDesc.BorderColor[1] = 0;
		samplerDesc.BorderColor[2] = 0;
		samplerDesc.BorderColor[3] = 0;
		samplerDesc.MinLOD = 0;
		samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

		// Create the texture sampler state.
		result = device->GetDevice()->CreateSamplerState(&samplerDesc, &mSampleState);
		if(FAILED(result))
		{
			return false;
		}

		D3D11_BUFFER_DESC matrixBufferDesc;
		// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
		matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
		matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
		matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
		matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		matrixBufferDesc.MiscFlags = 0;
		matrixBufferDesc.StructureByteStride = 0;

		// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
		result = device->GetDevice()->CreateBuffer(&matrixBufferDesc, NULL, &mMatrixBuffer);
		if(FAILED(result))
		{
			return false;
		}

		D3D11_BUFFER_DESC lightBufferDesc;
		// Setup the description of the light dynamic constant buffer that is in the pixel shader.
		// Note that ByteWidth always needs to be a multiple of 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail.
		lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
		lightBufferDesc.ByteWidth = sizeof(LightBufferType);
		lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
		lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		lightBufferDesc.MiscFlags = 0;
		lightBufferDesc.StructureByteStride = 0;

		// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
		result = device->GetDevice()->CreateBuffer(&lightBufferDesc, NULL, &mLightBuffer);
		if(FAILED(result))
		{
			return false;
		}
		return true;
	}
	return false;
}

void TerrainShader::DeinitializeShader()
{
	Shader::DeinitializeShader();
}

bool TerrainShader::SetShaderParameters(D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, Light* light, Texture* texture)
{
	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();
	Shader::SetShaderParameters(device, worldMatrix, viewMatrix, projectionMatrix);
	
	// Lock the light constant buffer so it can be written to.
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	HRESULT result = device->GetDeviceContext()->Map(mLightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	CHECK(result);

	// Get a pointer to the data in the constant buffer.
	LightBufferType* dataPtr2;
	dataPtr2 = (LightBufferType*)mappedResource.pData;

	// Copy the lighting variables into the constant buffer.
	dataPtr2->ambientColor = light->GetAmbientColor();
	dataPtr2->diffuseColor = light->GetDiffuseColor();
	dataPtr2->lightDirection = light->GetDirection();
	dataPtr2->padding = 0.0f;

	// Unlock the constant buffer.
	device->GetDeviceContext()->Unmap(mLightBuffer, 0);

	// Set the position of the light constant buffer in the pixel shader.
	unsigned int bufferNumber = 0;

	// Finally set the light constant buffer in the pixel shader with the updated values.
	device->GetDeviceContext()->PSSetConstantBuffers(bufferNumber, 1, &mLightBuffer);

	// Set shader texture resource in the pixel shader.
	if(texture)
	{
		ID3D11ShaderResourceView* d3dTexture = texture->GetResource();
		device->GetDeviceContext()->PSSetShaderResources(0, 1, &d3dTexture);
	}
	return true;
}